package com.heima.behavior.service.impl;

import com.heima.behavior.dtos.ReadBehaviorDto;
import com.heima.behavior.pojos.ApReadBehavior;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.ApThreadLocalUtil;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {
    @Resource
    private MongoTemplate mongoTemplate;
    /**
     * 点赞
     * @param dto
     */
    @Override
    public ResponseResult readBehavior(ReadBehaviorDto dto) {
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser apUser = ApThreadLocalUtil.getApUser();
        if(apUser == null && apUser.getId() == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApReadBehavior one = mongoTemplate.findOne(
                Query.query(
                        Criteria.where("userId").is(apUser.getId()).and("articleId").is(dto.getArticleId())
                ), ApReadBehavior.class
        );
        if(one != null){
            // 新增到数据库
            one.setCount(one.getCount()+1);
            one.setUpdatedTime(new Date());
            mongoTemplate.save(one);
        }else{
            one =new ApReadBehavior();
            one.setArticleId(dto.getArticleId());
            one.setCreatedTime(new Date());
            one.setUpdatedTime(new Date());
            one.setUserId(apUser.getId().longValue());
            one.setCount(1);
            mongoTemplate.insert(one);
        }
        return ResponseResult.okResult("成功");
    }

}
